import { ref, onMounted, onBeforeUnmount } from 'vue';

export function useRequestAnimationFrame(callback, interval) {
    const isRunning = ref(false);
    let lastTime = 0;
    let animationFrameId;

    const tick = (timestamp) => {
        if (!lastTime) {
            lastTime = timestamp;
        }
        const elapsed = timestamp - lastTime;
        if (elapsed >= interval) {
            callback();
            lastTime = timestamp;
        }
        if (isRunning.value) {
            animationFrameId = requestAnimationFrame(tick);
        }
    };

    const start = () => {
        if (!isRunning.value) {
            isRunning.value = true;
            lastTime = 0;
            animationFrameId = requestAnimationFrame(tick);
        }
    };

    const stop = () => {
        if (isRunning.value) {
            isRunning.value = false;
            cancelAnimationFrame(animationFrameId);
        }
    };

    onMounted(() => {
        start();
    });

    onBeforeUnmount(() => {
        stop();
    });

    return {
        start,
        stop
    };
}
